﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Modbus.Net8.Commom
{
    internal static class CodeExtensions
    {
        /// <summary>
        /// BCD是一种数据编码方式，它将十进制数字编码为二进制形式。在BCD编码中，每个十进制数字（0到9）被编码为4位二进制数（也称为一个 nibble）。
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static int FromBCD(this byte[] bytes)
        {
            bool last = false;
            int count = 0;
            for (int i = 0; i < bytes.Length; i++)
            {
                last = i == bytes.Length - 1;
                int hi = (int)(bytes[i] >> 4) * 10;
                int lo = (int)(bytes[i] & 0x0F);
                if (!last)
                {
                    count = count * 100 + hi + lo;
                }
                else
                {
                    if (hi == 0)
                        count = count * 10 + lo;
                    else
                        count = count * 100 + hi + lo;
                }
            }
            return count;
        }
        //int cnt = new byte[] { 0x45, 7 }.FromBCD();

        public static byte[] ToBCD(this int bytes)
        {
            string numberStr = bytes.ToString();
            byte[] bcd = new byte[(numberStr.Length + 1) / 2];

            int idx = 0;
            while (idx < bcd.Length)
            {
                int data = 0;
                data = (numberStr[idx * 2] - '0');
                if (idx * 2 + 1 < numberStr.Length)
                {
                    data = data * 16 + numberStr[idx * 2 + 1] - '0';
                }
                bcd[idx++] = (byte)(data);
            }
            return bcd;
        }
        //byte[] bytes = 457.ToBCD();




        /// <summary>
        /// byte[]转16进制字符串
        /// </summary>
        /// <param name="data"></param>
        /// <param name="clear"></param>
        /// <returns></returns>
        public static string ToHexStr(this byte[] data, bool clear = true)
        {
            string strData = BitConverter.ToString(data);
            if (clear)
                strData = strData.Replace("-", "");
            return strData;
        }

        public static byte[] FromHexStr(this string data)
        {
            return Convert.FromHexString(data); //C# 7.2及以上            
        }
    }
}
